<?php
/**
 * Created by PhpStorm.
 * User: aoc
 * Date: 2018/6/19
 * Time: 18:59
 */
namespace app\api\controller\vi\controller\order;

use app\api\controller\Api;
use app\api\controller\v1\model\order\Order as OM;
use think\Db;

class Order extends api
{
    public function Add()
    {
        //开启数据库事务处理
        Db::startTrans();
        try{
            if(request()->isPost())
            {
                //获取post中的userid
                $post = request()->post();
                $user_id = $post("user_id");

                //向订单表中插入一条空数据
                $data = [
                    'user_id' => $user_id,
                    'status' => OM::CREATEORDER,
                    'create_time' => time(),
                ];
                //insertGetId添加数据成功返回主键值  获得orderid
                $order_id = Db::table(ym_order)->insertGetId($data);
                if(!$order_id)
                {
                    throw new \Exception();
                }
                //向orderdetail表中添加数据
                //首先接受提交过来post中的内容，每个内容为一个商品
                foreach($post('OrderDetail') as $product) {
                    $product['order_id'] = $order_id;
                    $product['create_time'] = time();
                    $data['OrderDetail'] = $product;
                    $detail_id = Db::table(ym_order_detail)->insertGetId();
                    if(!$detail_id)
                    {
                        throw new \Exception();
                    }
                    //预留清空购物车
                    //预留使用完代金券，更新代金券的方法

                }

            }
            Db::commit();
        }catch(\Exception $e) {
            //数据回滚
            Db::rillback();
            //返回失败提示
            return $this->returnmsg(401,'数据库崩溃');
        }
        //成功返回订单id
        return $this->returnmsg(200,'success',['order_id' => $order_id]);
    }
}